/**
 * $Id: LuaScript.java Dec 16, 2014 4:43:07 PM hdp
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.aurora.app.constant;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

/**
 * Lua脚本使用类
 * <p>创建时间: Dec 16, 2014 4:43:07 PM</p>
 * @author <a href="mailto:hongdanping@163.com">hdp</a>
 * @version V1.0
 * @since V1.0
 */
public final class LuaScript {
	
	private LuaScript() {
		throw new RuntimeException("can't init");
	}
	/**
	 * 已经存在
	 */
	public static final String REDIS_RESULT_EXISTS = "exists";
	
	/**
	 * 1 红包列表   2 已经抢到的红包   3 红包与人的关系   4 用户
	 */
	public final static String TRY_GET_HONG_BAO_SCRIPT = 
			"if redis.call('hexists', KEYS[3], KEYS[4]) ~= 0 then\n"
					+ "return '" + REDIS_RESULT_EXISTS+ "'\n"
			+ "else\n"
				+ "local hongBao = redis.call('rpop', KEYS[1]);\n"
				+ "if hongBao then\n"
					+ "redis.call('hset', KEYS[3], KEYS[4], hongBao);\n"
					+ "redis.call('lpush', KEYS[2], hongBao);\n"
					+ "return hongBao;\n"
				+ "end\n"
			+ "end\n"
			+ "return nil";
	/**
	 * 抢红包lua文件
	 */
	private static final DefaultRedisScript<String> tryGetScript;
	
	static {
		try {
//			tryGetScript = new DefaultRedisScript<String>(TRY_GET_HONG_BAO_SCRIPT, String.class);
			tryGetScript = new DefaultRedisScript<String>();
			tryGetScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("META-INF/lua/get.lua")));
			tryGetScript.setResultType(String. class);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	/**
	 * 获取抢红包lua
	 * @return the trygetscript
	 */
	public static DefaultRedisScript<String> getTrygetscript() {
		return tryGetScript;
	}
}
